package top.sehnsucht;

import org.apache.log4j.Logger;
import top.sehnsucht.dao.UserPhotoDao;
import top.sehnsucht.dao.impl.UserPhotoDaoImpl;
import top.sehnsucht.service.UserPhotoService;
import top.sehnsucht.service.impl.UserPhotoServiceImpl;
import top.sehnsucht.util.DateFormatUtil;
import top.sehnsucht.vo.UserInfo;
import top.sehnsucht.vo.UserPhoto;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;


public class JDBCServlet extends HttpServlet {
    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        logger.debug(req.getSession().getServletContext().getAttribute("allFilename"));
        logger.debug(req.getSession().getServletContext().getAttribute("allPicUrls"));
        logger.debug(req.getParameter("username"));
        logger.debug(req.getParameter("birthday"));


        String allFilename = req.getSession().getServletContext().getAttribute("allFilename").toString();
        String[] splitFilename = allFilename.split(",");
        String allPicUrls = req.getSession().getServletContext().getAttribute("allPicUrls").toString();
        String[] splitPicUrls = allPicUrls.split(",");

        UserPhotoDao userPhotoDao = new UserPhotoDaoImpl();
        UserPhotoService userPhotoService = new UserPhotoServiceImpl(userPhotoDao);


        UserInfo userInfo = new UserInfo(req.getParameter("username"), DateFormatUtil.tran(req.getParameter("birthday")));

        Integer id = userPhotoService.addUser(userInfo);


        ArrayList<UserPhoto> userPhotos = new ArrayList<>();
        for (int i = 1; i < splitFilename.length; i++) {
            UserPhoto userPhoto = new UserPhoto(id, splitFilename[i], splitPicUrls[i]);
            userPhotos.add(userPhoto);
        }

        userPhotoService.addUserAndPhoto(userPhotos);


        String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort() + "/list.jsp";
        resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        resp.setHeader("Location", strBackUrl);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
